package com.example.h1nson.realphotography.asyncTask;

import android.graphics.Bitmap;
import android.os.AsyncTask;

import com.example.h1nson.realphotography.config.ConfigURL;
import com.example.h1nson.realphotography.config.GetCurrentUser;
import com.example.h1nson.realphotography.entity.Photo;
import com.example.h1nson.realphotography.interface_photo.OnDataFinishedListener;
import com.example.h1nson.realphotography.util.BitmapToString;
import com.example.h1nson.realphotography.util.HttpClientPost;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by H1nson on 2016/5/16.
 */
public class UploadPhotoAsynTask extends AsyncTask<String, Integer, String> {
    private OnDataFinishedListener onDataFinishedListener;
    private String jsonReqStr;
    private String URL;
    public UploadPhotoAsynTask(Photo photo, Bitmap bm){
        this.URL = URL;
        JSONObject jsonReq = new JSONObject();
        try{
            jsonReq.put("photoOwner",photo.getPhotoOwner());
            jsonReq.put("photoURL",photo.getPhotoUrl());
            jsonReq.put("photoLongitude",photo.getLongtitude());
            jsonReq.put("photoLatitude",photo.getLatitude());
            jsonReq.put("photoAddress",photo.getPhotoAddress());
            int year = photo.getPhotoDate().getYear()+1900;
            int month = photo.getPhotoDate().getMonth()+1;
            int date = photo.getPhotoDate().getDate();
            jsonReq.put("photoDate",year+"-"+month+1+"-"+date);
            jsonReq.put("photoNegativeCom",photo.getPhotoNegativeCom());
            jsonReq.put("photoActiveCom",photo.getPhotoActiveCom());
            if(bm!=null){
                jsonReq.put("hasBitmap",true);
                jsonReq.put("bitmap", BitmapToString.bitmapToBase64(bm));
            }else
                jsonReq.put("hasBitmap",false);
        }catch (JSONException e){
            e.printStackTrace();
        }
        this.jsonReqStr = jsonReq.toString();
    }
    public void setOnDataFinishedListener(OnDataFinishedListener onDataFinishedListener){
        this.onDataFinishedListener = onDataFinishedListener;
    }
    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        if(s!=null){
            onDataFinishedListener.onDataSuccessfully(s);
        }
        else onDataFinishedListener.onDataFailed();
    }

    @Override
    protected String doInBackground(String... params) {
        HttpClientPost post = new HttpClientPost(ConfigURL.uploadPhotoURL,jsonReqStr);
        post.doPost();
        return post.getJsonStrRes();
    }
}
